package leetcode.weekly.week301;

//Solution3Test
public class Solution3 {

	final char blank = '_';
	final char L = 'L';
	final char R = 'R';

	public boolean canChange(String start, String target) {
		char[] ss = start.toCharArray();
		char[] tt = target.toCharArray();
		int len = tt.length;
		for (int i = 0; i < len; i++) {
			char s = ss[i], t = tt[i];
			if (s != t) {
				if (t == blank) {
					if (s == this.L) {
						return false;
					} else if (s == this.R) {
						int s1 = 0;
						int t1 = 0;
						while (i < len && ss[i] != this.L && tt[i] != this.L) {
							if (ss[i] == this.R) {
								s1++;
							}
							if (tt[i] == this.R) {
								t1++;
							}
							if (s1 == t1) {
								break;
							}
							i++;
						}
						if (t1 != s1) {
							return false;
						}
					}
				} else if (t == this.L) {
					if (s == this.R) {
						return false;
					} else if (s == this.blank) {
						int s1 = 0;
						int t1 = 0;
						while (i < len && ss[i] != this.R && tt[i] != this.R) {
							if (ss[i] == this.L) {
								s1++;
							}
							if (tt[i] == this.L) {
								t1++;
							}
							if (s1 == t1) {
								break;
							}
							i++;
						}
						if (t1 != s1) {
							return false;
						}
					}
				} else if (t == this.R) {
					return false;
				}
			}
		}
		return true;
	}

	public boolean canChange1(String start, String target) {
		char[] ss = start.toCharArray();
		char[] tt = target.toCharArray();
		int len = tt.length;
		for (int i = 0; i < len; i++) {
			char s = ss[i], t = tt[i];
			if (s != t) {
				if (t == blank) {
					if (s == this.L) {
						return false;
					} else if (s == this.R) {
						int p = i;
						while (p < len && tt[p] != this.R) {
							if (tt[p] == this.L) {
								return false;
							}
							p++;
						}
						if (p == len) {
							return false;
						}
						i++;
						while (i < p) {
							if (ss[i] != this.blank) {
								return false;
							}
							i++;
						}
						if (ss[i] == this.L) {
							return false;
						} else if (ss[i] == this.R) {
							tt[i--] = '_';
						}
					}
				} else if (t == this.L) {
					if (s == this.R) {
						return false;
					} else if (s == this.blank) {
						int p = i;
						while (p < len && ss[p] != this.L) {
							if (ss[p] == this.R) {
								return false;
							}
							p++;
						}
						if (p == len) {
							return false;
						}
						i++;
						while (i < p) {
							if (tt[i] == this.R) {
								return false;
							} else if (tt[i] == this.L) {
								ss[p] = this.blank;
								break;
							}
							i++;
						}
						if (ss[i] == this.blank) {
							i--;
						} else if (tt[i] != this.blank) {
							return false;
						}
					}
				} else if (t == this.R) {
					return false;
				}
			}
		}
		return true;
	}

}
